package database

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"go-tzv/config"
)

// ConnectDB 连接数据库
func ConnectDB(config *config.Config) (*sql.DB, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", config.Database.User, config.Database.Password, config.Database.Host, config.Database.Port, config.Database.DBName)
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil, err
	}
	if err := db.Ping(); err != nil {
		db.Close()
		return nil, err
	}
	return db, nil
}

// UpdatePrice 更新数据库价格信息
func UpdatePrice(db *sql.DB, apiSymbol string, priceArr map[string]string) error {
	query := `
        UPDATE tw_ctmarket
        SET open = ?, close = ?, high = ?, low = ?, amount = ?, third_update_time = ?, last_update_time = UNIX_TIMESTAMP(NOW())
        WHERE symbol = ?
    `
	_, err := db.Exec(query,
		priceArr["open"],
		priceArr["close"],
		priceArr["high"],
		priceArr["low"],
		priceArr["amount"],
		priceArr["third_update_time"],
		apiSymbol,
	)
	return err
}
